import healthDataService from '../services/healthData.js';
import Result from '../utils/result.js';

const healthDataController = {
    async getRealData(req, res) {
        const { userId } = req.params;
        const data = await healthDataService.getRealData(userId);

        return res.status(200).json(data);
    },

    async getHistory(req, res) {
        try {
            console.log(req.params);
            const { userId } = req.params;
            const { startDate, endDate } = req.query;

            if (!userId) {
                return res.status(400).json(Result.error('Invalid userId').toObject());
            }

            if (!startDate || !endDate) {
                const today = new Date();
                startDate = new Date(today.setHours(0, 0, 0, 0)); // 当天的起始时间 00:00:00
                endDate = new Date(today.setHours(23, 59, 59, 999)); // 当天的结束时间 23:59:59
            }

            // 验证日期格式
            const dateRegex = /^\d{4}-\d{2}-\d{2}$/;

            if (!startDate || !dateRegex.test(startDate) || isNaN(new Date(startDate).getTime())) {
                return res.status(400).json(Result.error('Invalid startDate').toObject());
            }

            if (!endDate || !dateRegex.test(endDate) || isNaN(new Date(endDate).getTime())) {
                return res.status(400).json(Result.error('Invalid endDate').toObject());
            }

            const data = await healthDataService.getHistory(userId, startDate, endDate);

            return res.status(200).json(data);
        } catch (error) {
            console.log(error);
            return res.status(500).json(Result.error(error.message).toObject());
        }
    },

    async getStatistics(req, res) {

        const { userId } = req.params;
        const { period, type } = req.query;

        if(!period || !['day','week', 'month'].includes(period)){
            return res.status(400).json(Result.error('Invalid period').toObject());
        }
    

        const data = await healthDataService.getStatistics(userId, period, type);

        return res.status(200).json(data);
    },
};

export default healthDataController;
